//
//  QLMAddDevicesVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/13.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMAddDevicesVC.h"

#import "QLMAddDeviceTopCell.h"
#import "QLMAddDeviceMidCell.h"
#import "QLMAddDeviceBotCell.h"
#import "QLMAddressBookModel.h"

#import <IQKeyboardManager.h>
#import "QLMPhotoInfoTabCell.h"

#import "QLMPreCarTypeVC.h"
#import "QLMBrandNameTypeVC.h"
#import "QLMSerialNameVC.h"

#import <CoreFoundation/CoreFoundation.h>

@interface QLMAddDevicesVC ()<UITableViewDataSource,UITableViewDelegate,QLMAddDeviceTopCellDelegate,QLMAddDeviceMidCellDelegate,CNContactPickerDelegate,QLMPhotoInfoTabCellDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CTAssetsPickerControllerDelegate,QLMAddDeviceBotCellDelegate,QLMBrandNameTypeVCDelegate,ABPeoplePickerNavigationControllerDelegate>{
    
    QLMAddDeviceMidCell *middleCell;
    QLMAddDeviceBotCell *botcell;
    QLMPhotoInfoTabCell *photocell;
    
    NSMutableArray *selectedPhotos;
    QLMPreCarTypeVC *preVC;
    QLMBrandNameTypeVC *brandNameTypeVC;
    QLMSerialNameVC *serialTypeVC;
}
@property (nonatomic,strong) QLMAddDeviceTopCell *topcell;
@property (nonatomic,strong) NSString *machineTypeId;
@property (nonatomic,strong) NSString *machineTypeName;

@property (nonatomic,strong) NSString *aBrandId;

@property (nonatomic,strong) NSMutableArray *serialNoDataArr;
@property (nonatomic,strong) NSMutableArray *machineIdArr;
@property (nonatomic,strong) NSMutableArray *itemArray;
@property (nonatomic,strong) NSDictionary *brandDic;
@property (nonatomic,strong) NSMutableDictionary *brandResultDic;

@property (nonatomic,assign) NSInteger selectedRow;
@property (nonatomic,assign) NSString  *selectedTime;

@property (nonatomic,strong) NSMutableArray *selectUrlArr;
@property (nonatomic,strong) NSArray *hotBrandArr;

@end

@implementation QLMAddDevicesVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"添加设备";
    
    _selectedRow=0;
    _hotBrandArr=[NSArray array];
    _selectUrlArr=[NSMutableArray array];
    _machineIdArr=[NSMutableArray array];
    _serialNoDataArr=[NSMutableArray array];
    _brandResultDic=[NSMutableDictionary dictionary];
    _brandDic=[NSDictionary dictionary];
    _itemArray=[NSMutableArray array];
    selectedPhotos=[NSMutableArray array];
    
//    if (_deviceInfoModel.brandId.length!=0) {
//        [_brandResultDic setObject:_deviceInfoModel.brandId forKey:@"brandId"];
//        [_brandResultDic setObject:_deviceInfoModel.modelId forKey:@"modelId"];
//        [_brandResultDic setObject:_deviceInfoModel.modelName forKey:@"modelName"];
//        [_brandResultDic setObject:_deviceInfoModel.brandName forKey:@"brandName"];
//        [_brandResultDic setObject:_deviceInfoModel.pictureId forKey:@"pictureId"];
//        [_brandResultDic setObject:_deviceInfoModel.machineTypeId forKey:@"machineTypeId"];
//    }
//
//    if (self.deviceInfoModel.pictureDetail.count!=0) {
//        for (QLMDevicePicModel *picDetailModel in self.deviceInfoModel.pictureDetail) {
//
//            NSString *ulrStr=[NSString stringWithFormat:@"%@%@",kBaseURL,picDetailModel.pathName];
//            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:ulrStr]];
//            UIImage *aimage = [UIImage imageWithData:data];
//            [selectedPhotos addObject:aimage];
//
//            [_selectUrlArr addObject:picDetailModel.pathName];
//        }
//    }
    
    UIView *tipview=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 30)];
    tipview.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:tipview];
    
    UILabel *_titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 5, kScreen_width-20, 20)];
    _titleLabel.backgroundColor = [UIColor whiteColor];
    _titleLabel.font = [UIFont systemFontOfSize:16.0f];
    _titleLabel.textColor = [UIColor redColor];
    _titleLabel.textAlignment = NSTextAlignmentLeft;
    
    NSString *telStr=@"带*号的地方属于必填项";
    NSMutableAttributedString *aString=[[NSMutableAttributedString alloc] initWithString:telStr];
    [aString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1, 1)];
    _titleLabel.attributedText=aString;
    [tipview addSubview:_titleLabel];
    
    CGRect devFrame=CGRectMake(0, 30, kScreen_width, kScreen_height-QLM_StatusBarAndNavigationBarHeight-30-40);
    
    UITableView *_devicetableview=[[UITableView alloc] initWithFrame:devFrame style:UITableViewStyleGrouped];
    _devicetableview.backgroundColor=[UIColor clearColor];
    _devicetableview.delegate=self;
    _devicetableview.dataSource=self;
    _devicetableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    _devicetableview.showsVerticalScrollIndicator=NO;
    _devicetableview.showsHorizontalScrollIndicator=NO;
    _devicetableview.tableFooterView=[UIView new];
    [self.view addSubview:_devicetableview];
    
    UIButton *sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sureButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
    sureButton.frame = CGRectMake(0, kScreen_height-QLM_StatusBarAndNavigationBarHeight-40-IOS11_OR_LATER_SPACE(34), kScreen_width, 40);
    [sureButton setTitle:@"提交" forState:UIControlStateNormal];
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureButton.backgroundColor=kButtonColor;
    sureButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
    [sureButton addTarget:self action:@selector(_addDeviceAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureButton];
    
    if (@available(iOS 11.0, *)) {
        _devicetableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    if (_deviceInfoModel.brandId.length!=0) {
        [_brandResultDic setObject:_deviceInfoModel.brandId forKey:@"brandId"];
        [_brandResultDic setObject:_deviceInfoModel.modelId forKey:@"modelId"];
        [_brandResultDic setObject:_deviceInfoModel.modelName forKey:@"modelName"];
        [_brandResultDic setObject:_deviceInfoModel.brandName forKey:@"brandName"];
        [_brandResultDic setObject:_deviceInfoModel.pictureId forKey:@"pictureId"];
        [_brandResultDic setObject:_deviceInfoModel.machineTypeId forKey:@"machineTypeId"];
    }
    
    if (self.deviceInfoModel.pictureDetail.count!=0) {
        for (QLMDevicePicModel *picDetailModel in self.deviceInfoModel.pictureDetail) {
            
            NSString *ulrStr=[NSString stringWithFormat:@"%@%@",kBaseURL,picDetailModel.pathName];
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:ulrStr]];
            UIImage *aimage = [UIImage imageWithData:data];
            if (aimage!=nil) {
                [selectedPhotos addObject:aimage];
            }
            [_selectUrlArr addObject:picDetailModel.pathName];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)requestBranddata{
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:_machineTypeId forKey:@"machineTypeId"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/test/equipment/brandList1" withParamers:paramerDic andBody:nil
                    success:^(id responseObject){
                        
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            [_itemArray removeAllObjects];
                            _brandDic=responseObject[@"brandList"];
                            _hotBrandArr=responseObject[@"hotBrand"];
                            
                            NSArray *kArrSort = [_brandDic allKeys];
                            NSArray *resultkArrSort = [kArrSort sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                                return [obj1 compare:obj2 options:NSNumericSearch];
                            }];
                            for (NSString *firstLetterStr in resultkArrSort) {
                                [_itemArray addObject:[_brandDic objectForKey:firstLetterStr]];
                            }
                            
                            [self pustToBrandNameVC];
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                        [self.view hideToastActivity];
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)addDeviceAlert{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定添加设备？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self commitDeviceAction];
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                         }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)commitDeviceAction{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:_brandResultDic[@"brandId"] forKey:@"brandId"];
    [dic setObject:_brandResultDic[@"modelId"] forKey:@"modelId"];
    [dic setObject:_brandResultDic[@"modelName"] forKey:@"modelName"];
    [dic setObject:_brandResultDic[@"brandName"] forKey:@"brandName"];
    [dic setObject:_brandResultDic[@"machineTypeId"] forKey:@"machineTypeId"];
    
    NSString *urlPathStr=nil;
    if (_isCanEnableEdit) {
        
        if ([_deviceInfoModel.pictureId length]!=0) {
            [dic setObject:_deviceInfoModel.pictureId forKey:@"pictureId"];
        }
        [dic setObject:_deviceInfoModel.equipmentId forKey:@"equipmentId"];
        urlPathStr=@"/test/equipmentManager/update";
    }else{
        urlPathStr=@"/test/equipmentManager/add";
    }
    
    if (_machineIdArr.count!=0) {
        [dic setObject:_machineIdArr[self.selectedRow] forKey:@"machineId"];
    }else{
        [dic setObject:@"" forKey:@"machineId"];
    }
    if (self.selectedTime.length!=0) {
        [dic setObject:self.selectedTime forKey:@"productionDate"];
    }
    [dic setObject:middleCell.phoneNumTextField.text forKey:@"mainMachinePhone"];
    [dic setObject:middleCell.truthNameTextField.text forKey:@"mainMachineName"];
    
    if (_topcell.othernameTF.text.length!=0) {
        [dic setObject:_topcell.othernameTF.text forKey:@"alias"];
    }
    
    if (botcell.descriptionTF.text.length!=0) {
        [dic setObject:botcell.descriptionTF.text forKey:@"remark"];
    }
    
    NSMutableArray *picArray=[NSMutableArray array];
    for (NSString *urlStr in _selectUrlArr) {
        NSString *actualUrlStr=[NSString stringWithFormat:@"%@",urlStr];
        NSDictionary *imageUrlDic=[NSDictionary dictionaryWithObjectsAndKeys:actualUrlStr,@"pathName", nil];
        [picArray addObject:imageUrlDic];
    }
    
    [dic setObject:picArray forKey:@"pictureDetail"];
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:urlPathStr withParamers:dic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            ETToast(@"请求成功！");
                            [self.navigationController popViewControllerAnimated:YES];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

#pragma mark - QLMAddDeviceBotCellDelegate
- (void)tapTFAction{
    [_serialNoDataArr removeAllObjects];
    [_machineIdArr removeAllObjects];
}

#pragma mark - QLMAddDeviceTopCellDelegate
- (void)_addDeviceAction{
    
    [self.view endEditing:YES];
    
    if ([_brandResultDic allKeys].count==0) {
        ETToast(@"请选择设备型号");
        return;
    }
    if (middleCell.phoneNumTextField.text.length==0) {
        ETToast(@"请选择或输入联系人手机号");
        return;
    }
    if (middleCell.truthNameTextField.text.length==0) {
        ETToast(@"请选择或输入联系人姓名");
        return;
    }
    
    [self addDeviceAlert];
}

- (void)tapDismissAction{
    [self.navigationController dismissViewControllerAnimated:NO completion:nil];
}

- (void)leftBackAction:(UIButton *)btn{
    if (btn.tag==1965) {
        [serialTypeVC.navigationController popViewControllerAnimated:YES];
    }else{
         [brandNameTypeVC.navigationController popViewControllerAnimated:YES];
    }
}

- (void)pushSelectTypeAction{
    
    [self.view endEditing:YES];
    self.navigationController.view.userInteractionEnabled=YES;
    self.view.userInteractionEnabled=YES;
    __weak QLMAddDevicesVC *weakself=self;
    
    preVC=[QLMPreCarTypeVC new];
    preVC.view.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapDismiss=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDismissAction)];
    [preVC.leftView addGestureRecognizer:tapDismiss];
    
    [preVC.leftButton addTarget:self action:@selector(tapDismissAction) forControlEvents:UIControlEventTouchUpInside];
    
    preVC.block=^(NSString *machineTypeId,NSString *machineTypeName){
        weakself.machineTypeId=machineTypeId;
        weakself.machineTypeName=machineTypeName;
        [weakself requestBranddata];
    };
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:preVC];
    self.definesPresentationContext = YES;
    preVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.2];
    nav.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.2];
    nav.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)pustToBrandNameVC{
    
    brandNameTypeVC=[QLMBrandNameTypeVC new];
    brandNameTypeVC.delegate=self;
    brandNameTypeVC.view.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapDismiss=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDismissAction)];
    [brandNameTypeVC.leftView addGestureRecognizer:tapDismiss];
    
    [brandNameTypeVC.leftButton addTarget:self action:@selector(leftBackAction:) forControlEvents:UIControlEventTouchUpInside];
    
    brandNameTypeVC.brandDic=[[NSMutableDictionary alloc] initWithDictionary:_brandDic];
    brandNameTypeVC.itemArray=_itemArray;
    brandNameTypeVC.hotBrandArr=_hotBrandArr;
    
    self.definesPresentationContext = YES;
    brandNameTypeVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.2];
    brandNameTypeVC.navigationController.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.2];
    
    [preVC.navigationController pushViewController:brandNameTypeVC animated:YES];
}

- (void)didselectItem:(NSDictionary *)brandDic{
    
    __weak QLMAddDevicesVC *weakself = self;
    serialTypeVC=[QLMSerialNameVC new];
    serialTypeVC.view.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapDismiss=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDismissAction)];
    [serialTypeVC.leftView addGestureRecognizer:tapDismiss];
    serialTypeVC.leftButton.tag=1965;
    [serialTypeVC.leftButton addTarget:self action:@selector(leftBackAction:) forControlEvents:UIControlEventTouchUpInside];
    serialTypeVC.machineTypeId=_machineTypeId;
    serialTypeVC.brandId=brandDic[@"brandId"];
    serialTypeVC.codeName=brandDic[@"codeName"];
    
    serialTypeVC.serialBlock=^(NSString *codeName,NSString *modelName,NSString *productName,NSDictionary *modelDic){
        [weakself.topcell.selectCarTypeBtn setTitle:[NSString stringWithFormat:@"%@%@",codeName,modelName] forState:UIControlStateNormal];
        weakself.brandResultDic=[NSMutableDictionary dictionaryWithDictionary:modelDic];
        [weakself.brandResultDic setObject:codeName forKey:@"brandName"];
        [weakself tapDismissAction];
    };
    
    self.definesPresentationContext = YES;
    serialTypeVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.2];
    serialTypeVC.navigationController.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.2];
    
    [brandNameTypeVC.navigationController pushViewController:serialTypeVC animated:YES];
}

- (void)timeSelectPickerAction{
    [self.view endEditing:YES];
    
//     __weak QLMAddDevicesVC *weakself=self;
    
    
//    [BRDatePickerView showDatePickerWithTitle:@"出厂日期" dateType:UIDatePickerModeDate defaultSelValue:nil minDateStr:@"" maxDateStr:[self currentDateString] isAutoSelect:YES resultBlock:^(NSString *selectValue) {
//        [_topcell.timeSelectBtn setTitle:selectValue forState:UIControlStateNormal];
//        self.selectedTime=selectValue;
//    }];
    
    
//    [BRDatePickerView showDatePickerWithTitle:@"UIDatePickerModeDate" dateType: defaultSelValue:nil minDate:nil maxDate:nil isAutoSelect:YES themeColor:[UIColor clearColor] resultBlock:^(NSString *selectValue) {
//        [_topcell.timeSelectBtn setTitle:selectValue forState:UIControlStateNormal];
//        self.selectedTime=selectValue;
//    }];
    
    
}

- (NSString *)currentDateString {
    return [self currentDateStringWithFormat:@"yyyy-MM-dd HH:mm:ss"];// 设置格式：yyyy-MM-dd HH:mm:ss
}

#pragma mark - 按指定格式获取当前的时间
- (NSString *)currentDateStringWithFormat:(NSString *)formatterStr {
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = formatterStr;
    NSString *currentDateStr = [formatter stringFromDate:currentDate];
    return currentDateStr;
}

- (void)textFieldDidChange:(UITextField *)textField{

    NSInteger strlengthInt=0;
    if (textField == middleCell.phoneNumTextField) {
        strlengthInt=11;
    }else if (textField == botcell.descriptionTF){
        strlengthInt=50;
    }
    
    if (textField.text.length > strlengthInt) {
        UITextRange *markedRange = [textField markedTextRange];
        if (markedRange) {
            return;
        }
        NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:strlengthInt];
        textField.text = [textField.text substringToIndex:range.location];
    }
    
}

#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==3) {
        return 0.1;
    }
    return 34;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView=[[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    headerView.userInteractionEnabled=YES;
    
    if (section!=3) {
        NSString *titleStr=@"基本信息";
        if (section==1) {
            titleStr=@"机主信息";
        }else if (section==2){
            titleStr=@"其他信息";
        }
        UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
        newButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        newButton.frame = CGRectMake(10, 5, 100, 24);
        [newButton setImage:[UIImage imageNamed:@"icon"] forState:UIControlStateNormal];
        [newButton setTitle:titleStr forState:UIControlStateNormal];
        [newButton setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
        newButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
        newButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        newButton.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        [headerView addSubview:newButton];
    }
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==3||section==2) {
        return 0.1;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 150;
    }else if (indexPath.section==1) {
        return 100;
    }else if (indexPath.section==2) {
        return 50;
    }
    return 130;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        _topcell=[QLMAddDeviceTopCell cellWithTableView:tableView];
        [_topcell _creatButtonMainUI];
        _topcell.delegate=self;
        _topcell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        if (_isCanEnableEdit) {
            NSString *cartypyStr=[NSString stringWithFormat:@"%@%@",_deviceInfoModel.brandName,_deviceInfoModel.modelName];
            [_topcell.selectCarTypeBtn setTitle:cartypyStr forState:UIControlStateNormal];
            [_topcell.timeSelectBtn setTitle:self.deviceInfoModel.productionDate forState:UIControlStateNormal];
            self.selectedTime=self.deviceInfoModel.productionDate;
        }
        
        _topcell.othernameTF.text=self.deviceInfoModel.alias;
        
        return _topcell;
    }else if (indexPath.section==1) {
        middleCell=[QLMAddDeviceMidCell cellWithTableView:tableView];
        middleCell.delegate=self;
        middleCell.selectionStyle=UITableViewCellSelectionStyleNone;
        if (_isCanEnableEdit) {
            middleCell.truthNameTextField.text=_deviceInfoModel.mainMachineName;
            middleCell.phoneNumTextField.text=_deviceInfoModel.mainMachinePhone;
        }else{
            middleCell.truthNameTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserName];
            middleCell.phoneNumTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginPhoneName];
        }
        
        [middleCell.phoneNumTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        return middleCell;
    }else if (indexPath.section==2){
        botcell=[QLMAddDeviceBotCell cellWithTableView:tableView];
        botcell.selectionStyle=UITableViewCellSelectionStyleNone;
        botcell.delegate=self;
        
        botcell.descriptionTF.text = _deviceInfoModel.remark;
        [botcell.descriptionTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        return botcell;
    }
    
    photocell=[QLMPhotoInfoTabCell cellWithTableView:tableView];
    photocell.delegate=self;
    photocell.isCanEditable=YES;
    photocell.selectedPhotos=selectedPhotos;
    photocell.selectionStyle=UITableViewCellSelectionStyleNone;
    return photocell;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - CNContactPicker Action
- (void)contactAddressBookAction{
    
    [self.view endEditing:YES];
    if(IOS9_OR_LATER){
        __block BOOL authorization=NO;
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        if (status == CNAuthorizationStatusAuthorized){
            authorization = YES;
        }else{
            CNContactStore *contactStore = [[CNContactStore alloc] init];
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                if (granted) {
                    // 成功
                    authorization = YES;
                    [self _presentToContactVC];
                } else {
                    // 失败
                    authorization = NO;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        ETToastWithDelay(@"此应用程序尚未获得访问“通讯录”的权限,请去系统设置中打开此应用的“通讯录”的权限",2);
                    });
                }
            }];
        }
        if (authorization) {
            [self _presentToContactVC];
        }
    }else{
        // 创建联系人选择控制器
        ABPeoplePickerNavigationController *pvc = [[ABPeoplePickerNavigationController alloc] init];
        pvc.peoplePickerDelegate = self;
        if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined){
            ABAddressBookRef bookRef = ABAddressBookCreate();
            ABAddressBookRequestAccessWithCompletion(bookRef, ^(bool granted, CFErrorRef error) {
                if (granted){
                    NSLog(@"授权成功!");
                    [self presentViewController:pvc animated:YES completion:nil];
                }else{
                    NSLog(@"授权失败!");
                }
            });
        }else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
            [self presentViewController:pvc animated:YES completion:nil];
        }
    }
}

// 选择某个联系人时调用
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    
    NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSString *nickname= [NSString stringWithFormat:@"%@%@",lastName,firstName];
    
    NSString *phoneNumber=nil;
    ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex count = ABMultiValueGetCount(multi);
    if (count!=0) {
        NSString *phone =(__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(multi,0);
        phoneNumber=phone;
    }
    
    NSString *attrStr=[[NSString alloc] initWithString:phoneNumber];
    NSString *attrStr1=[attrStr  stringByReplacingOccurrencesOfString:@"(" withString:@""];
    NSString *attrStr2=[attrStr1 stringByReplacingOccurrencesOfString:@")" withString:@""];
    NSString *attrStr3=[attrStr2 stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *attrStr4=[attrStr3 stringByReplacingOccurrencesOfString:@" " withString:@""];
    middleCell.phoneNumTextField.text=[attrStr4 stringByReplacingOccurrencesOfString:@"-" withString:@""];
    middleCell.truthNameTextField.text=[NSString stringWithFormat:@"%@",nickname];
}

- (void)_presentToContactVC{
    CNContactPickerViewController *contactController = [[CNContactPickerViewController alloc] init];
    contactController.delegate = self;
    contactController.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
    [self presentViewController:contactController animated:YES completion:nil];
}

#pragma mark - CNContactPickerViewController delegate
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty{
    
    QLMAddressBookModel *addressBookModel=[[QLMAddressBookModel alloc] init];
    addressBookModel.givenName=contactProperty.contact.givenName;
    addressBookModel.middleName=contactProperty.contact.middleName;
    addressBookModel.familyName=contactProperty.contact.familyName;
    addressBookModel.organizationName=contactProperty.contact.organizationName;
    addressBookModel.phoneNumbers=contactProperty.contact.phoneNumbers;
    
    if (addressBookModel.phoneNumbers.count==0) {
        return;
    }
    CNLabeledValue *labeledValue=(CNLabeledValue *)addressBookModel.phoneNumbers[0];
    CNPhoneNumber *phoneValue = labeledValue.value;
    NSString *phoneNumber = phoneValue.stringValue;
    
    NSString *attrStr=[[NSString alloc] initWithString:phoneNumber];
    NSString *attrStr1=[attrStr  stringByReplacingOccurrencesOfString:@"(" withString:@""];
    NSString *attrStr2=[attrStr1 stringByReplacingOccurrencesOfString:@")" withString:@""];
    NSString *attrStr3=[attrStr2 stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *attrStr4=[attrStr3 stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    middleCell.phoneNumTextField.text=[attrStr4 stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    middleCell.truthNameTextField.text=[NSString stringWithFormat:@"%@%@%@",addressBookModel.givenName,addressBookModel.middleName,addressBookModel.familyName];
}


#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(buttonIndex == 0){
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        picker.showsNumberOfAssets = YES;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:NULL];
    }else if(buttonIndex == 1){
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        // picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }else if(buttonIndex == 2){
        return;
    }
}

#pragma mark - UIImagepicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [selectedPhotos addObject:image];
        photocell.selectedPhotos=selectedPhotos;
        [self uploadImageData:selectedPhotos];
    }];
}

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray<PHAsset*> *)assets{
    /** 关闭图片选择控制器*/
    [picker dismissViewControllerAnimated:YES completion:^{
        CGFloat scale = [UIScreen mainScreen].scale;
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.resizeMode = PHImageRequestOptionsResizeModeExact;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        
        NSMutableArray *tmpImgArray=[NSMutableArray array];
        /** 遍历选择的所有图片*/
        for (NSInteger i = 0; i < assets.count; i++) {
            PHAsset *asset = assets[i];
            CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
            
            /** 获取图片*/
            [[PHImageManager defaultManager] requestImageForAsset:asset
                                                       targetSize:size
                                                      contentMode:PHImageContentModeDefault
                                                          options:options
                                                    resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                        [tmpImgArray addObject:result];
                                                        if (tmpImgArray.count==assets.count) {
                                                            [selectedPhotos addObjectsFromArray:tmpImgArray];
                                                            photocell.selectedPhotos=selectedPhotos;
                                                            [self uploadImageData:selectedPhotos];
                                                        }
                                                    }];
        }
        
        
    }];
}

- (void)uploadImageData:(NSMutableArray *)userHeaderImageArray{
    
    [_selectUrlArr removeAllObjects];
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSMutableDictionary *tokenDic=[NSMutableDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    if ([token length]==0) {
        return;
    }
    
    ETToast(@"正在上传图片");
    [self.view makeToastActivity:CSToastPositionCenter];
    NSString *urlString=[NSString stringWithFormat:@"%@%@",kBaseURL,@"/rest/appUpload"];
    [ClientTool postUrlPath:urlString withParamers:tokenDic type:userHeaderImageArray success:^(id responseObject) {
        [self.view hideToastActivity];
        NSInteger status = [[responseObject objectForKey:@"flag"] integerValue];
        if (status == 1){
            ETToast([responseObject objectForKey:@"msg"]);
            _selectUrlArr=[NSMutableArray arrayWithArray:responseObject[@"list"]];
        }else{
            ETToast([responseObject objectForKey:@"msg"]);
        }
    } failure:^(NSError *error) {
        [self.view hideToastActivity];
        ETToast(@"服务器连接失败");
    }];
}

/** 相片的最大选择数方法*/
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset {
    NSInteger max = 5;
    if (picker.selectedAssets.count+selectedPhotos.count+1 > max) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"最多可选择5张照片" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [picker presentViewController:alert animated:YES completion:nil];
        return NO;
    }
    return YES;
}

#pragma mark - QLMPhotoInfoTabCellDelegate
- (void)deleteImageVAction:(NSInteger)itemTag{
//    NSLog(@"itemTag = %ld",itemTag);
    [_selectUrlArr removeObjectAtIndex:itemTag];
//    [selectedPhotos removeObjectAtIndex:itemTag];
}

- (void)selPhotoImageBtnAction{
    [self.view endEditing:YES];
    
    UIActionSheet *cameraSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    cameraSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
    [cameraSheet showInView:self.view];
}

- (BOOL)isAssetCanSelect:(id)asset {
    return NO;
}

- (void)tapPreViewerAction:(NSInteger)itemTag{//预览照片
    [XLPhotoBrowser showPhotoBrowserWithImages:selectedPhotos currentImageIndex:itemTag];
}

@end
